package handler

import (
	"context"
	"fmt"
	"gitee.com/DonHz/cloud-file-storage/service/account/proto"
	"github.com/gin-gonic/gin"
	"github.com/go-micro/plugins/v4/registry/consul"
	"go-micro.dev/v4"
	"go-micro.dev/v4/registry"
	"log"
	"net/http"
)

var (
	// 用于访问 rpc 的 client
	userCli proto.UserService
)

func init() {
	registry := consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))
	// 初始化 rpc 客户端
	service := micro.NewService(
		micro.Name("go.micro.api.user"),
		micro.Registry(registry),
	)
	// 初始化，解析命令行参数
	service.Init()
	// 初始化一个rpc client
	userCli = proto.NewUserService("go.micro.service.user", service.Client())
}

func SignUpHandler(c *gin.Context) {
	type SignUpReq struct {
		Phone          string `json:"phone"`
		Password       string `json:"password"`
		UserName       string `json:"username"`
		RepeatPassword string `json:"passwordc"`
	}
	var req SignUpReq
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Println(err)
		c.JSON(400, gin.H{
			"msg": "参数错误",
		})
		return
	}
	resp, err := userCli.SignUp(context.Background(), &proto.ReqSignUp{
		Phone:    req.Phone,
		Password: req.Password,
		Username: req.UserName,
	})
	if err != nil {
		log.Println(err)
		c.Status(http.StatusInternalServerError)
		return
	}
	c.JSON(200, gin.H{
		"code": resp.Code,
		"msg":  resp.Msg,
	})
}

func SignInHandler(c *gin.Context) {
	type SignInReq struct {
		UserName string `json:"username"`
		Password string `json:"password"`
	}
	var req SignInReq
	// 解析请求参数
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Println("参数错误：", err)
		c.JSON(400, gin.H{
			"msg": "参数错误",
		})
		return
	}
	// 校验参数
	resp, err := userCli.SignIn(context.Background(), &proto.ReqSignIn{
		Username: req.UserName,
		Password: req.Password,
	})
	if err != nil {
		log.Println(err)
		c.JSON(500, gin.H{
			"msg": "手机号或密码错误",
		})
		c.Status(http.StatusInternalServerError)
		return
	}
	c.Set("token", resp.Token)
	c.Set("user", req.UserName)
	c.JSON(200, gin.H{
		"code": resp.Code,
		"msg":  resp.Msg,
		"data": gin.H{
			"token":    resp.Token,
			"username": req.UserName,
		},
	})
}

func UserInfoHandler(c *gin.Context) {
	//校验token
	req := struct {
		Phone string `json:"username"`
		Token string `json:"token"`
	}{
		Phone: c.Query("username"),
		Token: c.Query("token"),
	}
	// 查询用户信息
	resp, err := userCli.GetUserInfo(context.Background(), &proto.ReqUserInfo{
		Username: req.Phone,
		Token:    req.Token,
	})
	if err != nil {
		fmt.Println(err)
		c.JSON(500, gin.H{
			"msg": "系统错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": resp.Code,
		"msg":  resp.Msg,
		"data": resp.User,
	})
}
